import os

import requests
from loguru import logger


def gitee(ver, message, prerelease: bool = False):
    """
    在 Gitee 上创建发布版本

    :param ver: 版本号
    :param message: 发布信息
    :param prerelease: 是否为预发布版本，默认为 False
    :return: 无
    """
    # 配置信息
    GITEE_ACCESS_TOKEN = os.getenv('GITEE_ACCESS_TOKEN')
    if GITEE_ACCESS_TOKEN is None:
        print("请设置环境变量 GITEE_ACCESS_TOKEN")
        exit(1)
    logger.debug("GITEE_ACCESS_TOKEN: " + GITEE_ACCESS_TOKEN)
    OWNER = 'liumou_site'
    REPO = 'gns'
    TAG_NAME = f'v{ver}'
    NAME = f'Version {ver}'

    # 构建请求 URL
    url = f'https://gitee.com/api/v5/repos/{OWNER}/{REPO}/releases'

    # 构建请求体
    data = {
        'tag_name': TAG_NAME,
        'name': NAME,
        'body': message,
        'target_commitish': 'master',
        'owner': OWNER,
        'repo': REPO,
        'prerelease': prerelease,
        'access_token': GITEE_ACCESS_TOKEN
    }

    # 发送 POST 请求
    response = requests.post(url, data=data)

    # 检查响应
    if response.status_code == 201:
        logger.info('Release created successfully!')
        logger.info(response.json())
    else:
        logger.error(f'Failed to create release: {response.status_code}')
        logger.error(response.text)
        logger.error(response.request)
        exit(2)


if __name__ == '__main__':
    gitee(ver='1.5.7', message='master', prerelease=False)
